import React, { memo, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Helmet } from 'react-helmet';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { compose } from 'redux';
import { useInjectSaga } from '../../utils/injectSaga';
import { useInjectReducer } from '../../utils/injectReducer';
import makeSelectBlog from './selectors';
import reducer from './reducer';
import { componentDidMountAction } from './actions';
import saga from './saga';
import messages from './messages';
import Nodes from './nodes';
import { Row, Col, Anchor, Affix } from 'antd';
import RainbowBaseCard from '../../components/RainbowBaseCard';
import RainbowCard from '../../components/RainbowCard';
import RainbowMarked from '../../components/RainbowMarked';

const { Link } = Anchor;

export function Blog(props) {
  useInjectReducer({ key: 'blog', reducer });
  useInjectSaga({ key: 'blog', saga });
  const [catalogue, setCatalogue] = useState([]);

  const renderCatalogue = item => (
    <Link key={item.text} href={`#${item.text}`} title={item.text} data-scroll-to={`#${item.text}`}>
      {item.children.length ? item.children.map(renderCatalogue) : ''}
    </Link>
  );

  useEffect(() => {
    props.componentDidMountAction();
  }, []);

  return (
    <Nodes.Container id="Blog" data-scroll-section>
      <FormattedMessage {...messages.header}>
        {title => (
          <Helmet>
            <title>{title}</title>
            <meta name="description" content="Description of Home" />
          </Helmet>
        )}
      </FormattedMessage>
      <Nodes.Content>
        <Row>
          <Col span={20} data-scroll>
            <RainbowMarked
              getCatalogue={item => {
                setCatalogue(item);
              }}
            />
          </Col>
          <Col span={4}>
            <RainbowCard style={{ marginLeft: '10px', marginBottom: '10px' }} />
            <Affix target={window} offsetTop={100}>
              <RainbowBaseCard style={{ textAlign: 'left', marginLeft: '10px' }}>
                <Anchor>{catalogue.length ? catalogue.map(renderCatalogue) : ''}</Anchor>
              </RainbowBaseCard>
            </Affix>
          </Col>
        </Row>
      </Nodes.Content>
    </Nodes.Container>
  );
}

Blog.propTypes = {
  dispatch: PropTypes.func.isRequired,
};

const mapStateToProps = createStructuredSelector({
  blog: makeSelectBlog(),
});

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
    componentDidMountAction: () => dispatch(componentDidMountAction()),
  };
}

const withConnect = connect(mapStateToProps, mapDispatchToProps);

export default compose(withConnect, memo)(Blog);
